package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        List<Element> list = rootElement.selectNodes("//insert | //delete | // update | //select");
        String namespace = rootElement.attributeValue("namespace");

        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement(id, resultType, parameterType, sql);

            if ("insert".equalsIgnoreCase(element.getName())){
                mappedStatement.setType(MappedStatement.Type.INSERT);
            } else if ("delete".equalsIgnoreCase(element.getName())){
                mappedStatement.setType(MappedStatement.Type.DELETE);
            } else if ("update".equalsIgnoreCase(element.getName())){
                mappedStatement.setType(MappedStatement.Type.DELETE);
            } else if ("select".equalsIgnoreCase(element.getName())){
                mappedStatement.setType(MappedStatement.Type.SELECT);
            }
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
